﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.yeepay.bank;
using FortuneHeavenBAL;
using FortuneHeavenCommon.DataMap;
using FortuneHeavenCommon.Enum;
using System.Text;

namespace FortuneHeaven.Web.Pages.Charge
{
    public partial class ChargeCallBack : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // 校验返回数据包
                BuyCallbackResult result = Buy.VerifyCallback(FormatQueryString.GetQueryString("p1_MerId"), FormatQueryString.GetQueryString("r0_Cmd"), FormatQueryString.GetQueryString("r1_Code"), FormatQueryString.GetQueryString("r2_TrxId"),
                    FormatQueryString.GetQueryString("r3_Amt"), FormatQueryString.GetQueryString("r4_Cur"), FormatQueryString.GetQueryString("r5_Pid"), FormatQueryString.GetQueryString("r6_Order"), FormatQueryString.GetQueryString("r7_Uid"),
                    FormatQueryString.GetQueryString("r8_MP"), FormatQueryString.GetQueryString("r9_BType"), FormatQueryString.GetQueryString("rp_PayDate"), FormatQueryString.GetQueryString("hmac"));

                if (string.IsNullOrEmpty(result.ErrMsg))
                {
                    //在接收到支付结果通知后，判断是否进行过业务逻辑处理，不要重复进行业务逻辑处理
                    if (result.R1_Code == "1")
                    {
                        #region 更新数据库
                        AccountsInfoBO bo = new AccountsInfoBO();
                        AccountsInfo acount = bo.GetLightAcountInfor(result.R8_MP);
                        RechargeHistoryBO chargebo = new RechargeHistoryBO();
                        RechargeHistory existrecord = chargebo.GetChargeByCode(result.R2_TrxId);
                        int chargevalue = (int)decimal.Parse(result.R3_Amt);
                        UserInforBO userbo = new UserInforBO();
                        UserInfor customer = userbo.GetUserInfor(acount.UserID);
                        if (existrecord == null)
                        {
                            if (customer == null)
                            {
                                customer = new UserInfor();
                                customer.UserID = acount.UserID;
                            }
                            customer.FortuneValue = customer.FortuneValue + chargevalue;
                            userbo.SaveUserInfor(customer);
                            AccountsInfo target = bo.GetAcount(acount.SpreaderID);
                            DateTime time = DateTime.Now;
                            if (target != null)
                            {
                                UserInfor spreaduser = userbo.GetUserInfor(acount.SpreaderID);
                                //推广积分换算比例
                                int spreadvalue = (int)(chargevalue * 5);
                                if (spreaduser != null)
                                {
                                    spreaduser.SpreadValue = spreaduser.SpreadValue + spreadvalue;
                                }
                                else
                                {
                                    spreaduser = new UserInfor();
                                    spreaduser.UserID = acount.SpreaderID;
                                    spreaduser.SpreadValue = spreadvalue;
                                }
                                userbo.SaveUserInfor(spreaduser);
                                UserSpreadBO spreadrecord = new UserSpreadBO();
                                UserSpread sp = new UserSpread();
                                sp.UserID = target.UserID;
                                sp.FromUserID = acount.UserID;
                                sp.FromUserName = acount.Accounts;
                                sp.RechargeType = (int)SpreadType.charge;
                                sp.Remark = "推广用户使用银行冲值";
                                sp.Value = spreadvalue;
                                sp.DateTime = time;
                                sp.ID = spreadrecord.GetMaxID();
                                spreadrecord.Save(sp, true);
                            }
                            RechargeHistoryBO history = new RechargeHistoryBO();
                            RechargeHistory his = new RechargeHistory();
                            his.RechargeValue = chargevalue;
                            his.CardCode = result.R2_TrxId;
                            his.RechargeType = (int)RechargeType.Bank;
                            his.Time = time;
                            his.UserID = acount.UserID;
                            history.Add(his);
                        }
                        #endregion

                        if (result.R9_BType == "1")
                        {
                            //  callback方式:浏览器重定向
                            //Response.Write("支付成功!<br>商品ID:" + result.R5_Pid + "<br>商户订单号:" + result.R6_Order + "<br>支付金额:" + result.R3_Amt + "<br>易宝支付交易流水号:" + result.R2_TrxId + "<BR>userid:"+result.R8_MP);                        
                            //Response.Redirect("ChargeNetPaySuccess.aspx?fortune=" + chargevalue);

                            if (customer != null && existrecord != null && existrecord.IsComplete !=1)
                            {
                                string from = customer.FromPage != null ? customer.FromPage.ToLower() : "";
                                StringBuilder builder = new StringBuilder();
                                //搜宝
                                if (from == "index3.aspx")
                                {
                                    builder.Append(string.Format(@"<script language=javascript>
var price='{0}';
var orders = '{1}' //订单号
var proportion = '25'; 
var like='';  //原样返回
</script>
<script language=javascript src="" http://www.soo-boo.com/cpa.js""></script> ", chargevalue, result.R2_TrxId));

                                }

                                //新迅
                                if (from == "index1.aspx")
                                {
                                    builder.Append(string.Format(@"<iframe src=""http://jump.newsxun.com/api/cpa.php?orders={0}&price={1}&like="" height=0 width=0></iframe>", result.R2_TrxId, chargevalue));
                                }
                                //E元素
                                if (from == "index2.aspx")
                                {
                                    builder.Append(string.Format(@"<iframe src=""http://www.eys100.com/api/cpa.php?orders={0}&price={1}&like="" height=0 width=0></iframe>", result.R2_TrxId, chargevalue));
                                }
                                //广告人
                                if (from == "index4.aspx")
                                {
                                    builder.Append(string.Format(@"<iframe src=""http://www.adsmen.com/api/cpa.php?orders={0}&price={1}&like="" height=0 width=0></iframe>", result.R2_TrxId, chargevalue));
                                }
                                this.ltTransfer.Text = builder.ToString();
                                existrecord.IsComplete = 1;
                                chargebo.Save(existrecord);
                            }
                            ClientScript.RegisterStartupScript(this.GetType(), "transfer", string.Format("document.location='{0}'; ", ("ChargeNetPaySuccess.aspx?fortune=" + chargevalue)), true);
                        }
                        else if (result.R9_BType == "2")
                        {
                            // * 如果是服务器返回则需要回应一个特定字符串'SUCCESS',且在'SUCCESS'之前不可以有任何其他字符输出,保证首先输出的是'SUCCESS'字符串                            
                            Response.Write("SUCCESS");
                            //this.SpreadCharge.Text = "";
                        }
                    }
                    else
                    {
                        Response.Write("支付失败!");

                    }
                }
                else
                {
                    Response.Write("交易签名无效!");
                }
            }
        }
    }
}